﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Web;

namespace up6.db.utils
{
    public class JsonTool
    {
        /// <summary>
        /// 将json指定字段转换成数组
        /// </summary>
        /// <param name="arr"></param>
        /// <param name="field"></param>
        /// <returns>a,b,c,d,e,f,g</returns>
        public static String[] toArray(JToken arr,string field="name") { 
            List<String> result = new List<String>();
            foreach (JObject item in arr)
            {
                result.Add(item[field].ToString().Trim());
            }
            return result.ToArray();
        }

        /// <summary>
        /// 将JArray中的字段合并成一个字符串
        /// </summary>
        /// <param name="arr"></param>
        /// <param name="tmp"></param>
        /// <param name="separator"></param>
        /// <returns>[a],[b],[c],[d]</returns>
        public static string merge(JToken arr, string tmp="{0}", string field = "name", string separator = ",")
        {
            List<string> list = new List<string>();
            foreach (JObject o in arr)
            {
                list.Add(string.Format(tmp, o[field].ToString().Trim()));
            }
            return string.Join(separator, list.ToArray());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="arr"></param>
        /// <param name="tmp"></param>
        /// <param name="field"></param>
        /// <param name="separator"></param>
        /// <returns></returns>
        public static string[] mergeArray(JToken arr, string tmp = "{0}", string field = "name", string separator = ",")
        {
            List<string> list = new List<string>();
            foreach (JObject o in arr)
            {
                list.Add(string.Format("[{0}]", o[field].ToString().Trim()));
            }
            return list.ToArray();
        }

        /// <summary>
        /// 根据字段名称获取JSON对象
        /// </summary>
        /// <param name="names"></param>
        /// <param name="fields"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static JToken getObjects(string[] names, JToken fields, string key = "name")
        {
            var keys = UtilsTool.toDic(names);

            List<JObject> arr = new List<JObject>();
            foreach (JObject o in fields)
            {
                if (keys.ContainsKey(o[key].ToString().Trim()))
                {
                    arr.Add(o);
                }
            }
            return JToken.FromObject(arr);
        }
    }
}